//
//  NSString+Utils.m
//  Pods
//
//  Created by YCJ on 2016/12/22.
//
//

#import "NSString+Utils.h"
//#import "NSData+Utils.h"
#import "NSData+Utils.h"


@implementation NSString (Utils)

// json字符串解析字典
- (NSDictionary *)dictionary
{
    if (self == nil) {
        return nil;
    }
    
    NSData *jsonData = [self dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err){
        NSLog(@"字符串解析为字典失败：%@",err);
        return nil;
    }
    return dic;
}

/**
 *  判断字符串不为空
 *
 *  @return 当为YES, string不为nil, 并且length大于0
 */
- (BOOL)isNonEmpty {
    
    BOOL isNonEmpty = ![self isEqual:[NSNull null]] && self.length > 0;
    
    return isNonEmpty;
}

/**
 *  对网址进行编码
 *
 */
- (NSString *)encodedURLQuery {
    return [self stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
}

- (NSString *)sha1Hash {
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    NSData *hash = [data sha1HashData];
    return [hash hexString];
}

- (NSString *)md5Hash {
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    NSData *hash = [data md5HashData];
    return [hash hexString];
}

- (CGFloat)percentStringToFloat {
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setNumberStyle:NSNumberFormatterPercentStyle];
    NSNumber *number = [formatter numberFromString:self];
    
    return [number doubleValue];
}

/**
 将浮点数转化为百分比
 
 @param value e.g 0.75
 @return e.g 75%
 */
- (NSString *)percentStringWithFloat:(CGFloat)value {
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setNumberStyle:NSNumberFormatterPercentStyle];
    
    return [formatter stringFromNumber:@(value)];
}

/**
 *  @brief  格式话小数 四舍五入类型
 *
 *  @param format 格式例如 0.000 ，保留三位小数
 *  @param value 数字
 *
 */
+ (NSString *)decimalwithFormat:(NSString *)format floatValue:(CGFloat)value {
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setPositiveFormat:format];
    
    return  [numberFormatter stringFromNumber:[NSNumber numberWithDouble:value]];
}

- (NSString *)base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)options {
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    return [data base64EncodedStringWithOptions:options];
}

- (NSData *)base64EncodedDataWithOptions:(NSDataBase64EncodingOptions)options {
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    return [data base64EncodedDataWithOptions:options];
}

- (id)JSONObject:(NSJSONReadingOptions)options error:(NSError **)outError {
    return [NSJSONSerialization JSONObjectWithData:[self dataUsingEncoding:NSUTF8StringEncoding] options:options error:outError];
}

@end
